如何将Fork的Draggable库导入Angular2项目?
Hey there, totally get the frustration of hunting for solutions and coming up empty—don’t worry about this being a common question, we’ve all been stuck on finicky import problems like this! Let’s break down what’s going on here and walk through some practical fixes for your forked Draggable library:
The Core Problem
Your forked library is a plain .js file without ES module syntax (no import/export statements), so trying to import it directly as a module will fail. Renaming it to .ts doesn’t help because TypeScript only adds type checking—it won’t magically add the module structure the browser/bundler expects.
Practical Solutions to Try
Here are a few approaches that should get you up and running:
Add module exports directly to the forked file
Open the downloaded.jsfile, scroll to the very end, and add an export statement for the main Draggable class/function. For example, if the library exposes a globalDraggablevariable, add:export default Draggable;Now you can import it like any other module in your project:
import Draggable from './path/to/your/forked/draggable.js';Use a script tag + global variable declaration
If you don’t want to modify the library’s source code, include it via a traditional script tag in your HTML:<script src="./path/to/forked/draggable.js"></script>Then, in your JS/TS files, declare the global variable to avoid linting/type errors:
// For TypeScript declare const Draggable: typeof import('your-draggable-type-defs'); // Or for plain JS, just use window.Draggable directly const draggableInstance = new window.Draggable(...);Create a wrapper module
Make a small wrapper file (e.g.,draggable-wrapper.js) that loads the library and exports the global variable as a module:// Load the library to attach it to window import './path/to/forked/draggable.js'; // Export the global as a module export default window.Draggable;Then import from the wrapper instead:
import Draggable from './draggable-wrapper.js';Configure your bundler (if using Webpack/Vite/Rollup)
If you’re using a bundler, you can set it up to handle the non-module library:- Webpack: Use the
ProvidePluginto auto-inject the global variable into your modules:// webpack.config.js const webpack = require('webpack'); module.exports = { plugins: [ new webpack.ProvidePlugin({ Draggable: './path/to/forked/draggable.js' }) ] }; - Vite: Add an alias or use
optimizeDepsto pre-process the library. For example, invite.config.js:export default { resolve: { alias: { 'draggable': './path/to/forked/draggable.js' } } };
- Webpack: Use the
If you can share a bit more about your project setup (like which bundler or framework you’re using), I can help refine these steps even further!
内容的提问来源于stack exchange,提问作者Scilef

